﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DotNET4Study
{
    public class ChangeTypeStudy
    {
        public static void Execute()
        {
            string dateTimeString = "2011-10-5";
            ////1.普通类型的转换
            //DateTime resut = (DateTime)Convert.ChangeType(dateTimeString, typeof(DateTime));

            ////2.可空值类型的转换（其会抛出异常）
            //DateTime? resut = (DateTime?)Convert.ChangeType(dateTimeString,typeof(DateTime?));

            //3.使用扩展后的转换工具对可空值类型的转换就可以进行
            DateTime? resut = (DateTime?)ChangeType(dateTimeString, typeof(DateTime?));

            Console.WriteLine(resut.ToString());
        }

        public static object ChangeType(object value, Type conversionType)
        {
            if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
            {

                if (value == null)
                {
                    return null;
                }

                System.ComponentModel.NullableConverter nullableConverter
                    = new System.ComponentModel.NullableConverter(conversionType);

                conversionType = nullableConverter.UnderlyingType;
            }

            return Convert.ChangeType(value, conversionType);
        }

    }
}
